import json
import time
import hmac
import base64
import hashlib
import requests
import urllib.parse
from utils.config import config
from utils.logger import logger


def dingtalkSign(secret):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    result = {
        "time": timestamp,
        "sign": sign
    }
    logger.info(result)
    return result


def wechatSend(content: str):
    global data, params

    url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send"
    headers = {"Content-Type": "application/json"}

    for webhook in config.wechat_webhooks():
        logger.info({"key": webhook})
        params = {
            "key": webhook
        }
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": content
            }
        }

        response = requests.post(url=url, params=params, headers=headers, data=json.dumps(data)).json()
        logger.info({"response": response})
        return response


def dingtalkSend(content: str):
    global data, params

    url = "https://oapi.dingtalk.com/robot/send"
    headers = {"Content-Type": "application/json"}

    for bot_name, webhook in config.dingtalk_webhooks().items():
        logger.info(bot_name)
        token = webhook['token']
        secret = webhook['secret']
        sign = dingtalkSign(secret)
        params = {
            "access_token": token,
            "timestamp": sign['time'],
            "sign": sign['sign']
        }
        data = {
            "msgtype": "markdown",
            "markdown": {
                "title": "告警",
                "text": content
            },
            "at": {
                "atMobiles": [],
                "isAtAll": False
            }
        }

        response = requests.post(url=url, params=params, headers=headers, data=json.dumps(data)).json()
        if response['errcode'] != 0:
            logger.error({"response": response})
        logger.info({"content": data, "response": response})
        return response


